<template>
  <el-button type="primary" size="medium" @click="export_excel" :loading="export_loading">导出</el-button>
</template>

<script>
import ExcelJs from 'exceljs'
export default {
  props: ['products'],
  data() {
    return {
      export_loading: false,
    }
  },
  methods: {
    async export_excel() {
      this.export_loading = true
      const workbook = new ExcelJs.Workbook()
      const worksheet = workbook.addWorksheet('Sheet1')
      worksheet.columns = [
        { header: '品牌', key: 'brand', width: 15 },
        { header: '型号', key: 'model', width: 10 },
        { header: '运行内存', key: 'ram', width: 10 },
        { header: '存储容量', key: 'storage', width: 10 },
        { header: '颜色', key: 'color', width: 10 },
        { header: '串码', key: 'imei', width: 30 },
        { header: '库存数量', key: 'count', width: 10 },
      ]
      for (let i = 0; i < this.products.length; i++) {
        const product = this.products[i]
        for (let j = 0; j < product.imei.length; j++) {
          worksheet.addRow({
            brand: product.brand,
            model: product.model,
            ram: product.ram,
            storage: product.storage,
            color: product.color,
            imei: product.imei[j],
            count: product.count,
          })
        }
      }
      const buffer = await workbook.xlsx.writeBuffer()
      const blob = new Blob([buffer], { type: 'application/vnd.ms-excel' })
      const href = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.style.display = 'none'
      a.href = href
      a.download = `filename.xlsx`
      a.click()
      this.export_loading = false
      this.$message({
        type: 'success',
        message: '导出成功',
      })
      URL.revokeObjectURL(a.href)
    },
  },
}
</script>
